import * as turf from '@turf/turf';
import Core from "../../cesiumJs/Core/Core";
import getPosition from "../../cesiumJs/Core/getPosition"

/**
 * 缓冲区分析。
 * @alias BufferAnalysis
 * @constructor
 */
function BufferAnalysis(viewer, cesium, option) {
  this._viewer = viewer;
  this._cesium = cesium;
  this._scene = viewer.scene;
  this._core = new Core();
  this._getPosition = new getPosition(viewer);

  this._stretch = option.radio //1:同时拉伸缓冲区和绘制面 2：只拉伸缓冲面
  this.num = option.r;
  this._maxh = option.maxh
  this._minh = option.minh
  this.buffs = [];
  this.tooltip = this._core.CreateTooltip();
  this.buffPosition = null
  this.innerRingPos = null
}

/**
 * 设置缓冲区大小
 * @param {Number} [value] 半径，米
 */
BufferAnalysis.prototype.changeBurr = function (value) {
  this.num = value;
  if (this.this_buff) {
    switch (this.type) {
      case 'point':
        this.setPointBuff(this.num);
        break;
      case 'polyline':
        this.setPolylineBuff(this.num);
        break;
      case 'polygon':
        this.setPolygonBuff(this.num);
        break;
    }
  }
};

/**
 * 画点
 *
 * @param {Number|Object} radiusOrOption 半径或参数
 * @param {Function} [callback] 回调函数
 */
BufferAnalysis.prototype.DrawPoint = function (radiusOrOption, callback) {
  if (this.drawHandler) {
    this.drawHandler.destroy();
    this.drawHandler = null;
  }
  this.this_buff && this.this_buff.entity && this._viewer.entities.remove(this.this_buff.entity);
  var Viewer = this._viewer;
  var Cesium = this._cesium;
  let num, option;
  if (typeof radiusOrOption === "number") {
    num = radiusOrOption;
    option = {};
  } else if (typeof radiusOrOption === "object") {
    option = radiusOrOption;
    num = option.radius;
  }
  this.num = num || this.num;
  this.drawHandler = new Cesium.ScreenSpaceEventHandler(Viewer.scene.canvas);
  this.this_buff = {
    entity: null,
    buff: null
  };
  this.type = 'point';
  this.positions = [];
  //设置鼠标样式
  //   this._core.mouse(this._viewer.container, 1, window.SmartEarthRootUrl + configData$1.draw);
  //鼠标左键单击
  this.drawHandler.setInputAction(function (movement) {
    var Degrees = this._getPosition.getMouseDegrees(movement);
    if (!Degrees) return;
    var longitude = Degrees.lon;
    var latitude = Degrees.lat;

    this.positions.push(longitude, latitude);
    this.this_buff.entity = Viewer.entities.add({
      name: "新建缓冲点",
      position: Cesium.Cartesian3.fromDegrees(longitude, latitude),
      point: {
        pixelSize: 10,
        color: Cesium.Color.YELLOW,
        outlineWidth: 3,
        outlineColor: Cesium.Color.YELLOW.withAlpha(0.4),
        heightReference: 1
      }
    });
    this.buffs.push(this.this_buff.entity);
    this.this_buff.entity = undefined;
    this.setPointBuff(this.num, option);
    callback && typeof callback === 'function' && callback(Degrees);
    this.end && this.end();
  }.bind(this), Cesium.ScreenSpaceEventType.LEFT_CLICK);

  this.end = () => {
    this.tooltip.show(false);
    this.drawHandler.destroy();
    //设置鼠标样式
    // this._core.mouse(this._viewer.container, 0);
    this.drawHandler = null;
    this.end = undefined;
  };

  //鼠标移动
  this.drawHandler.setInputAction(function (movement) {
    this.tooltip.showAt(movement.endPosition, "点击绘制点");
  }.bind(this), Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  return this;
};

/**
 * 设置点缓冲区大小
 * @param {Number} [radius] 半径，米
 *
 */
BufferAnalysis.prototype.setPointBuff = function (radius, option) {
  let pointF = turf.point(this.positions);
  let positions = this.getBuff(pointF, radius);
  if (!this.this_buff.buff) {
    this.this_buff.buff = this.addBufferPolyogn(positions, option);
    this.buffs.push(this.this_buff.buff);
  }
};

/**
 * 画线
 * @param {Number|Object} radiusOrOption 半径或参数
 * @param {Function} [callback] 回调函数
 */
BufferAnalysis.prototype.DrawPolyline = function (radiusOrOption, callback) {
  if (this.drawHandler) {
    this.drawHandler.destroy();
    this.drawHandler = null;
  }
  this.this_buff && this.this_buff.entity && this._viewer.entities.remove(this.this_buff.entity);
  var Viewer = this._viewer;
  var Cesium = this._cesium;

  let num, option;
  if (typeof radiusOrOption === "number") {
    num = radiusOrOption;
    option = {};
  } else if (typeof radiusOrOption === "object") {
    option = radiusOrOption;
    num = option.radius;
  }
  this.num = num || this.num;
  var clickNum = 0;
  this.drawHandler = new Cesium.ScreenSpaceEventHandler(Viewer.scene.canvas);
  this.this_buff = {
    entity: null,
    buff: null
  };
  this.type = 'polyline';
  this.positions = [];
  //设置鼠标样式
  //   this._core.mouse(this._viewer.container, 1, window.SmartEarthRootUrl + configData$1.draw);
  //鼠标左键单击
  this.drawHandler.setInputAction(function (movement) {
    var Degrees = this._getPosition.getMouseDegrees(movement);
    if (!Degrees) return;
    var longitude = Degrees.lon;
    var latitude = Degrees.lat;

    this.positions.push(longitude, latitude);
    if (clickNum === 0) {
      this.positions.push(longitude, latitude);
      this.this_buff.entity = Viewer.entities.add({
        name: "新建缓冲线",
        polyline: {
          positions: Cesium.Cartesian3.fromDegreesArray(this.positions),
          width: 2,
          material: new Cesium.ColorMaterialProperty(Cesium.Color.YELLOW),
          //material: Cesium.Color.YELLOW,
          clampToGround: true,
          zIndex: 1
        }
      });
      this.this_buff.entity.polyline.positions = new Cesium.CallbackProperty(function () {
        return Cesium.Cartesian3.fromDegreesArray(this.positions);
      }.bind(this), false);
    }
    clickNum++;
  }.bind(this), Cesium.ScreenSpaceEventType.LEFT_CLICK);

  //鼠标右键单击
  this.drawHandler.setInputAction(function (movement) {
    this.end && this.end();
  }.bind(this), Cesium.ScreenSpaceEventType.RIGHT_CLICK);

  this.end = (type) => {
    this.tooltip.show(false);
    this.drawHandler.destroy();
    //设置鼠标样式
    // this._core.mouse(this._viewer.container, 0);
    this.drawHandler = null;

    this.end = undefined;
    if (type === 'cancel') {
      Viewer.entities.remove(this.this_buff.entity);
      this.this_buff = undefined;
      return;
    }
    var that = this;
    if (this.positions.length <= 4) {
      window.layuiLayer && window.layuiLayer.msg("当前点数小于两点，请重新绘制");
      Viewer.entities.remove(this.this_buff.entity);
      this.this_buff = undefined;
      callback && typeof callback === 'function' && callback(that);
      return;
    }
    this.positions.pop();
    this.positions.pop();

    this.this_buff.entity.polyline.positions = Cesium.Cartesian3.fromDegreesArray(this.positions);

    this.buffs.push(this.this_buff.entity);
    this.this_buff.entity = undefined;
    this.positions = this.degreesArrayToPoints(this.positions);
    this.setPolylineBuff(this.num, option);
    callback && typeof callback === 'function' && callback(that);
  };

  //鼠标移动
  this.drawHandler.setInputAction(function (movement) {
    if (clickNum === 0) {
      this.tooltip.showAt(movement.endPosition, "点击开始绘制折线");
      return;
    } else if (clickNum === 1) {
      this.tooltip.showAt(movement.endPosition, "点击绘制折线");
    } else {
      this.tooltip.showAt(movement.endPosition, "右击结束绘制");
    }
    var Degrees = this._getPosition.getMouseDegrees(movement);
    if (!Degrees) return;
    var longitude = Degrees.lon;
    var latitude = Degrees.lat;
    this.positions.splice(this.positions.length - 2, 2);
    this.positions.push(longitude, latitude);
  }.bind(this), Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  return this;
};

/**
 * 设置线缓冲区大小
 * @param {Number} [radius] 半径，米
 *
 */
BufferAnalysis.prototype.setPolylineBuff = function (radius, option) {
  let polylineF = turf.lineString(this.positions);
  let positions = this.getBuff(polylineF, radius);
  if (!this.this_buff.buff) {
    this.this_buff.buff = this.addBufferPolyogn(positions, option);
    this.buffs.push(this.this_buff.buff);
  }
};

/**
 * 画面
 * @param {Number|Object} radiusOrOption 半径或参数
 * @param {Function} [callback] 回调函数
 */
BufferAnalysis.prototype.DrawPolygon = function (radiusOrOption, callback) {
  if (this.drawHandler) {
    this.drawHandler.destroy();
    this.drawHandler = null;
  }
  this.this_buff && this.this_buff.entity && this._viewer.entities.remove(this.this_buff.entity);
  var Viewer = this._viewer;
  var Cesium = this._cesium;

  let num, option;
  if (typeof radiusOrOption === "number") {
    num = radiusOrOption;
    option = {};
  } else if (typeof radiusOrOption === "object") {
    option = radiusOrOption;
    num = option.radius;
  }

  this.num = num || this.num;
  var clickNum = 0;
  this.drawHandler = new Cesium.ScreenSpaceEventHandler(Viewer.scene.canvas);
  this.this_buff = {
    entity: null,
    buff: null
  };
  this.type = 'polygon';
  this.positions = [];
  let that = this;
  //设置鼠标样式
  //   this._core.mouse(this._viewer.container, 1, window.SmartEarthRootUrl + configData$1.draw);
  //鼠标左键单击
  this.drawHandler.setInputAction(function (movement) {
    var Degrees = this._getPosition.getMouseDegrees(movement);
    if (!Degrees) return;
    var longitude = Degrees.lon;
    var latitude = Degrees.lat;
    this.positions.push(longitude, latitude);
    if (clickNum === 0) {
      this.positions.push(longitude, latitude);
      this.this_buff.entity = Viewer.entities.add({
        name: '临时线',
        polyline: {
          positions: new Cesium.CallbackProperty(function () {
            return Cesium.Cartesian3.fromDegreesArray(that.positions);
          }, false),
          clampToGround: true,
          material: new Cesium.ColorMaterialProperty(Cesium.Color.YELLOW.withAlpha(0.5)),
          width: 3,
        }
      });
    } else if (clickNum === 1) {
      this.this_buff.entity && Viewer.entities.remove(this.this_buff.entity);
      this.this_buff.entity = Viewer.entities.add({
        name: "新建缓冲面",
        polygon: {
          hierarchy: new Cesium.PolygonHierarchy(Cesium.Cartesian3.fromDegreesArray(this.positions)),
          material: new Cesium.ColorMaterialProperty(Cesium.Color.RED.withAlpha(0.5)),
          zIndex: 1
        }
      });
      this.this_buff.entity.polygon.hierarchy = new Cesium.CallbackProperty(function () {
        return new Cesium.PolygonHierarchy(Cesium.Cartesian3.fromDegreesArray(this.positions));
      }.bind(this), false);
    }
    clickNum++;
  }.bind(this), Cesium.ScreenSpaceEventType.LEFT_CLICK);

  //鼠标右键单击
  this.drawHandler.setInputAction(function (movement) {
    this.end && this.end();
  }.bind(this), Cesium.ScreenSpaceEventType.RIGHT_CLICK);

  this.end = (type) => {
    this.tooltip.show(false);
    this.drawHandler.destroy();
    //设置鼠标样式
    // this._core.mouse(this._viewer.container, 0);
    this.drawHandler = null;

    this.end = undefined;


    if (type === 'cancel') {
      Viewer.entities.remove(this.this_buff.entity);
      this.this_buff = undefined;
      return;
    }

    if (this.positions.length <= 6) {
      window.layuiLayer && window.layuiLayer.msg("当前点数小于三点，请重新绘制");
      Viewer.entities.remove(this.this_buff.entity);
      this.this_buff = undefined;
      callback && typeof callback === 'function' && callback(this);
      return;
    }
    this.positions.pop();
    this.positions.pop();

    if (this._stretch === '1') {
      Viewer.entities.remove(this.this_buff.entity);
      this.this_buff.entity = Viewer.entities.add({
        name: "拉伸面",
        polygon: {
          hierarchy: Cesium.Cartesian3.fromDegreesArray(this.positions),
          material: new Cesium.ColorMaterialProperty(Cesium.Color.RED.withAlpha(0.5)),
          height: this._maxh,
          extrudedHeight: this._minh,
          zIndex: 1
        }
      });
    }
    if (this._stretch === '2') {
      Viewer.entities.remove(this.this_buff.entity);
    }
    this.positions.push(this.positions[0],this.positions[1])
    this.innerRingPos = this.positions
    this.this_buff.entity.polygon.hierarchy = Cesium.Cartesian3.fromDegreesArray(this.positions);

    this.buffs.push(this.this_buff.entity);
    this.this_buff.entity = undefined;
    this.positions = this.degreesArrayToPoints(this.positions);
    // this.positions.push(this.positions[0]); //面闭合
    this.setPolygonBuff(this.num, option);
    // let polygonF = turf.polygon([this.positions]);
    // this.buffPosition = this.getBuff(polygonF, this.num);
    callback && typeof callback === 'function' && callback(this);
  };

  //鼠标移动
  this.drawHandler.setInputAction(function (movement) {
    if (clickNum === 0) {
      this.tooltip.showAt(movement.endPosition, "点击开始绘制多边形");
      return;
    } else if (clickNum < 3) {
      this.tooltip.showAt(movement.endPosition, "点击绘制多边形");
    } else {
      this.tooltip.showAt(movement.endPosition, "右击结束绘制");
    }
    var Degrees = this._getPosition.getMouseDegrees(movement);
    if (!Degrees) return;
    var longitude = Degrees.lon;
    var latitude = Degrees.lat;
    this.positions.splice(this.positions.length - 2, 2);
    this.positions.push(longitude, latitude);
  }.bind(this), Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  return this;
};

/**
 * 设置面缓冲区
 * @param {Number} [radius] 半径，米
 *
 */
BufferAnalysis.prototype.setPolygonBuff = function (radius, option) {
  let polygonF = turf.polygon([this.positions]);
  option.holes= []
  // option.holes.push({
  //   positions:Cesium.Cartesian3.fromDegreesArray(this.innerRingPos)
  // })
  let position = this.getBuff(polygonF, radius);
  if (!this.this_buff.buff) {
    this.this_buff.buff = this.addBufferPolyogn(position, option);
    this.buffs.push(this.this_buff.buff);
  } else {
    this._viewer.entities.remove(this.this_buff.buff)
    this.this_buff.buff = this.addBufferPolyogn(position, option);
    this.buffs.push(this.this_buff.buff);
  }
};

BufferAnalysis.prototype.changePolygonHeight = function (height) {
  if (this.buffs.length > 0) {
    for (let i = 0; i < this.buffs.length; i++) {
      const entity = this.buffs[i]
      entity.polygon.height = height
      this._maxh = height
    }
  }
}

BufferAnalysis.prototype.changePolygonExtrudedHeight = function (extrudedHeight) {
  if (this.buffs.length > 0) {
    for (let i = 0; i < this.buffs.length; i++) {
      const entity = this.buffs[i]
      entity.polygon.extrudedHeight = extrudedHeight
      this._minh = extrudedHeight
    }
  }
}

//获取缓冲区
BufferAnalysis.prototype.getBuff = function (geometry, radius, option = {}) {
  let buffered = turf.buffer(geometry, radius, {
    units: 'meters',
    ...option
  });
  let coordinates = buffered.geometry.coordinates;

  let degreesArray = this.pointsToDegreesArray(coordinates[0]);
  this.buffPosition = degreesArray
  let data = {
    positions: Cesium.Cartesian3.fromDegreesArray(degreesArray)
  };
  if (coordinates.length > 1) {
    data.holes = [];
    for (let i = 1, positions; i < coordinates.length; i++) {
      degreesArray = this.pointsToDegreesArray(coordinates[i]);
      
      positions = Cesium.Cartesian3.fromDegreesArray(degreesArray);
      data.holes.push(positions);
    }
  }
  return data;
};

//数组格式转换
BufferAnalysis.prototype.pointsToDegreesArray = function (points) {
  let degreesArray = [];
  points.map(item => {
    degreesArray.push(item[0]);
    degreesArray.push(item[1]);
  });
  return degreesArray;
};

//数组格式转换
BufferAnalysis.prototype.degreesArrayToPoints = function (degreesArray) {
  let points = [];
  for (let i = 0; i < degreesArray.length - 1; i += 2) {
    points.push([degreesArray[i], degreesArray[i + 1]]);
  }
  return points;
};

//添加缓冲面
BufferAnalysis.prototype.addBufferPolyogn = function (data, option = {}) {
  let positions, holes;
  positions = data.positions;
  if (option.holes) {
    holes = [];
    option.holes.forEach(item => {
      holes.push(item);
    });
  }
  return this._viewer.entities.add({
    polygon: {
      hierarchy: new Cesium.CallbackProperty(function () {
        return new Cesium.PolygonHierarchy(positions, holes);
      }, false),
      material: Cesium.Color.YELLOW.withAlpha(0.6),
      height: this._maxh,
      extrudedHeight: this._minh,
      outline: false,
      outlineColor: Cesium.Color.YELLOW,
      outlineWidth: 2,
      zIndex: 0,
      ...option
    },
  });
};

//清除
BufferAnalysis.prototype.clearBuff = function () {
  var Viewer = this._viewer;
  if (this.buffs.length > 0) {
    this.buffs.forEach(function (buff) {
      Viewer.entities.remove(buff);
    });
    this.buffs.length = 0;
  }
};


export default BufferAnalysis
